<template>
    <div>
      <canvas v-show="false" ref="canvas" :width="canvasWidth" :height="canvasHeight"></canvas>
      <div @click="generatePoster">生成海报</div>
    </div>
  </template>
  
  <script>
  import QRCode from 'qrcode';
  
  export default {
    data() {
      return {
        canvasWidth: 1415,
        canvasHeight: 1920,
        qrCodeText: '', // 替换为你的二维码内容
      };
    },
    mounted() {
    //   this.generatePoster();
    },
    methods: {
      async generatePoster() {
        const canvas = this.$refs.canvas;
        const ctx = canvas.getContext('2d');
  
        // 加载背景图
        const backgroundImage = new Image();
        backgroundImage.src = 'static/img/cavasBg.png'; // 替换为你的背景图片路径
        backgroundImage.onload = () => {
          ctx.drawImage(backgroundImage, 0, 0, this.canvasWidth, this.canvasHeight);
  
          // 生成二维码
          this.generateQRCode(this.qrCodeText).then(qrCodeDataURL => {
            const qrCodeImg = new Image();
            qrCodeImg.src = qrCodeDataURL;
            qrCodeImg.onload = () => {
              const qrCodeX = (this.canvasWidth - qrCodeImg.width) / 2;
              const qrCodeY = (this.canvasHeight - qrCodeImg.height) / 2;
              ctx.drawImage(qrCodeImg, qrCodeX, qrCodeY);
  
              // 将Canvas转换为DataURL
              const dataURL = canvas.toDataURL('image/png');
  
              // 创建一个隐藏的链接并自动点击下载
              this.downloadPoster(dataURL);
            };
          }).catch(error => {
            console.error('生成二维码出错：', error);
          });
        };
      },
      generateQRCode(text) {
        return new Promise((resolve, reject) => {
          QRCode.toDataURL(text, { width: 200, height: 200 }, (err, url) => {
            if (err) reject(err);
            else resolve(url);
          });
        });
      },
      downloadPoster(dataURL) {
        const link = document.createElement('a');
        link.href = dataURL;
        link.download = 'poster.png';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      }
    }
  };
  </script>
  